package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.yksj.healthtalk.adapter.ShopListViewAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.ShopListItemEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 商品搜索 通过名字
 * @author root
 *
 */
public class ServerShopSeachActivity extends BaseFragmentActivity implements OnClickListener, OnRefreshListener<ListView>, OnItemClickListener {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private String goods_ID;
	private String senderId;//发送者id
	private ShopListViewAdapter adapter;
	private String mName;
	private boolean flage = false;
	private Button seach_onclick;
	private EditText seach_text;
	private int str;
	private int page = 0;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.server_shop_seach_list);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		initTitle();
		if(getIntent().hasExtra("main")){//从主页进来 加商户id
			str = getIntent().getIntExtra("type", 0);
			mName = getIntent().getStringExtra("main");
			senderId = getIntent().getStringExtra("MERCHANT_ID");
		}else if(getIntent().hasExtra("name")){//通过名字查找
			mName = getIntent().getStringExtra("name");
			str = getIntent().getIntExtra("type", 0);
			senderId = getIntent().getStringExtra("id");
			flage=false;
		}else{//通过code查找
			mName = getIntent().getStringExtra("code");
			findViewById(R.id.seach_ui).setVisibility(View.GONE);
			flage=true;
		}
		initView();
	}
	
	private void initView(){
		titleTextV.setText("商品搜索");
		titleLeftBtn.setOnClickListener(this);
		
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		adapter = new ShopListViewAdapter(this, new ArrayList<ShopListItemEntity>());
		mPullToRefreshListView.setOnRefreshListener(this);
		mListView.setDivider(getResources().getDrawable(R.drawable.list_divider_bg));
		mListView.addFooterView(getLayoutInflater().inflate(R.layout.list_line_layout, null));
		mListView.setFooterDividersEnabled(true);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		seach_onclick = (Button)findViewById(R.id.seach_onclick);
		seach_onclick.setOnClickListener(this);
		seach_text = (EditText) findViewById(R.id.seach_text);
	
		seach_text.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId == EditorInfo.IME_ACTION_SEARCH){
					if(!HStringUtil.isEmpty(seach_text.getText().toString())){
						goods_ID = null;
						mName =seach_text.getText().toString().trim();
						flage=false;
						seach_text.setText(mName);
						page=0;
						initData(String.valueOf(Long.MAX_VALUE));
					}
					return true;
				}
				return false;
			}
		});
		
		seach_text.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length()>0){
					seach_onclick.setVisibility(View.VISIBLE);
				}else{
					seach_onclick.setVisibility(View.GONE);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		if(!flage){
			seach_text.setText(mName);
		}else{
			mPullToRefreshListView.setMode(Mode.DISABLED);
		}
		findViewById(R.id.deleteText).setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn.setVisibility(View.VISIBLE);
		
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
		
		titleRightBtn.setBackgroundResource(R.drawable.shopping_trolley);
		titleRightBtn2.setBackgroundResource(R.drawable.server_order);
		
		SystemUtils.hideSoftBord(getApplicationContext(), seach_text);
		initData(String.valueOf(Long.MAX_VALUE));
		
	}

	private void initData(final String valueOf) {
		HttpRestClient.doHttpServerShopByName(String.valueOf(++page),senderId,str,mName,valueOf,flage,new ObjectHttpResponseHandler(){
			@Override
			public Object onParseResponse(String content) {
				return ShopListItemEntity.parseToEntity(content);
			}
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				
				if(response == null)return;
				//第一次查询
				if(String.valueOf(Long.MAX_VALUE).equals(valueOf)){
					adapter.list.clear();
					adapter.changeData((List<ShopListItemEntity>)response);
				//下拉刷新	
				}else{
					adapter.changeData((List<ShopListItemEntity>)response);
				}
				if(adapter.list.size() > 0) {
					goods_ID = adapter.list.get(adapter.list.size()-1).getGOODS_ID();
				}else if(adapter.list.size()==0){
					ToastUtil.showToastPanl("暂无商品");
				}
			}
			@Override
			public void onStart() {
				super.onStart();
				mPullToRefreshListView.setRefreshing();
			}
			@Override
			public void onFinish() {
				super.onFinish();
				mPullToRefreshListView.onRefreshComplete();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.deleteText:
			seach_text.setText("");
			break;
		case R.id.seach_onclick:
			if(!seach_text.getText().toString().trim().equals("")){
				goods_ID = null;
				mName =seach_text.getText().toString().trim();
				flage=false;
				seach_text.setText(mName);
//				str=0;
				page=0;
				initData(String.valueOf(Long.MAX_VALUE));
			}
			break;
		case R.id.title_right:
			HttpRestClient.doHttpCartList(senderId,new TtrolleyHandler(2));
		break;
		case R.id.title_right2:
			Intent intent = new Intent(getApplicationContext(),ServerCenterOrderListActivity.class);
			intent.putExtra("merchant_id", senderId);
			startActivity(intent);
		break;
		}
		
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		initData(goods_ID);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent=new Intent(ServerShopSeachActivity.this,ServerCenterDescription.class);
		ShopListItemEntity entity = adapter.list.get(position-1);
		intent.putExtra("entity", entity);
		intent.putExtra("id", senderId);
		startActivity(intent);
	}
	
	class TtrolleyHandler extends JsonHttpResponseHandler {
		int type; // 1加入购物车 2查询购物车列表
		private ImageView buyImg;
		public TtrolleyHandler(int type) {
			super(ServerShopSeachActivity.this);
			this.type = type;
		}
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			try {
				if (response.has("info")) { 
					ToastUtil.showToastPanl(response.getString("info"));
				} else if (response.has("money")) {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", senderId);
					intent.putExtra("response", response.toString());
					startActivityForResult(intent, 1);
//					{}
				}else {
					Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
					intent.putExtra("MERCHANT_ID", senderId);
					startActivity(intent);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			super.onSuccess(statusCode, response);
		}
		@Override
		public void onSuccess(int statusCode, JSONArray response) {
			Intent intent = new Intent(getApplicationContext(),ServerCenterTrolleyActivity.class);
			startActivity(intent);
			super.onSuccess(statusCode, response);
		}
	}
	
}
